<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :showCollapse="true"
      :id="`inqu_${tableId}`"
      :searchNum="searchItemCount"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="code" label="代码">
          <FIInput v-model="state.query.code" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <!-- <FISelect
              @eidt-change="onCellChange"
              v-model="state.query.projectEname"
              valueCustom="value"
              :options="arr2"
              clearable
            /> -->
        <FIFormItem name="projectEname" label="项目代码">
          <FISelect
            v-if="arr2.length > 0"
            @eidt-change="onCellChange1"
            v-model="state.query.projectEname"
            valueCustom="value"
            :options="arr2"
            clearable
          />
          <!-- <FISelect
            v-model="state.query.projectEname"
            valueCustom="value"
            :options="[
              { value: '1', label: '是' },
              { value: '0', label: '否' },
            ]"
            v-model:key-word="keyWord"
            clearable
          /> -->
        </FIFormItem>
      </el-col>

      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem name="moduleEname" label="一级模块">
          <!-- {{arr1}} -->
          <FISelect v-model="state.query.moduleEname" valueCustom="value" :options="arr1" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="id"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @row-delete="deleteRow"
    >
      <template #projectEname="{ scope }">
        <FISelect
          @eidt-change="onCellChange($event, scope.$index)"
          v-if="scope.row.isSelected"
          v-model="scope.row.projectEname"
          valueCustom="value"
          :options="arr2"
          clearable
        />
        <span v-else>{{ scope.row.projectEname }}</span>
      </template>
      <template #moduleEname="{ scope }">
        <FISelect
          @focus="onfocusEvent($event, scope.$index)"
          @eidt-change="onCellChange($event, scope.$index)"
          v-if="scope.row.isSelected"
          v-model="scope.row.moduleEname"
          valueCustom="value"
          :options="arr1"
          clearable
        />
        <span v-else>{{ scope.row.moduleEname }}</span>
      </template>
      <template #lang="{ scope }">
        <FISelect
          @eidt-change="onCellChange($event, scope.$index)"
          v-if="scope.row.isSelected"
          v-model="scope.row.lang"
          valueCustom="value"
          :options="arr3"
          clearable
        />
        <span v-else>{{ scope.row.lang }}</span>
      </template>

      <!-- <template #moduleEname="{ scope }">
        

        <FISelect
          v-if="scope.row.isSelected"
          @eidt-change="onCellChange"
          v-model="scope.row.moduleEname"
          valueCustom="value"
          :options="scope.row.moduleEname1Options"
          clearable
        />

        <span v-else>{{ scope.row.moduleEname }}</span>
      </template> -->

      <!-- <template #headerBtn>
        <FIPopconfirmBtn
          title="您是否确认删除选中数据吗？"
          buttonText="删除"
          beforePopText="请选择一条数据"
          :btn-binds="{ id: 'delete', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="deleteRow"
        >
        </FIPopconfirmBtn>
      </template> -->
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import {
  apiGettipcodeMaintQuery,
  apiGettipcodeMaintSave,
  apiGettipcodeMaintDel,
  apiGetModule1,
  apiGetbackproject,
} from '@/api/configEnvMaint/index.ts'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiQueryCodeitem } from '@/api/common'
const route = useRoute()

const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'tipcodeMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)

const state = reactive({
  query: {
    projectEname: '',
    code: '',
    moduleEname: '',
    dynamicParams: [],
    orderbyParams: [],
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  // {
  //   label: '页面ID',
  //   prop: 'formId',
  //   align: 'center',
  //   width: '120',
  //   editable: false,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },

  {
    label: '项目英文名',
    prop: 'projectEname',
    align: 'center',
    editable: true,
    // filterable: true,
    // sortable: true,
    // editType: 'select',
    modelValue: [],
    // configValueToLable: {
    //   list: [
    //     { value: '1', label: '启用' },
    //     { value: '0', label: '禁用' },
    //   ],
    // },
    editConfig: {
      rules: { projectEname: [{ required: true, message: '请输入类型', trigger: 'blur' }] },
      // options: [
      //   { value: '1', label: '启用' },
      //   { value: '0', label: '禁用' },
      // ],
      codeOption: { codesetCode: 'menuType' },
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '一级模块名',
    prop: 'moduleEname',
    align: 'center',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    // editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' },
      ],
    },
    editConfig: {
      options: [
        { value: '1', label: '启用' },
        { value: '0', label: '禁用' },
      ],
      codeOption: { codesetCode: 'menuType' },
      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '代码',
    prop: 'code',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    editType: 'input',
    editable: true,
    readonly: true,
    // filterable: true,
    // sortable: true,
    sortValue: '',
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { code: [{ required: true, message: '请输入代码', trigger: 'blur' }] },
    },
  },
  {
    label: '语言',
    prop: 'lang',
    align: 'center',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editConfig: {
      rules: { lang: [{ required: true, message: '请输入文本', trigger: 'blur' }] },
    },
  },
  {
    label: '文本',
    prop: 'text',
    align: 'center',
    editable: true,
    // filterable: true,
    // sortable: true,
    modelValue: { inputValue: '' },
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    editConfig: {
      rules: { text: [{ required: true, message: '请输入文本', trigger: 'blur' }] },
    },
  },

  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
])
const arr1 = ref([])
const checkedRows = ref([])
const onfocusEvent = (e, index) => {
  getModuleData(tableRef.value.cloneTableData[index].projectEname, index)
}
const onCellChange = (e, index) => {
  // state.query.moduleEname = ''
  getModuleData(e, index)
}
const onCellChange1 = (e, index) => {
  state.query.moduleEname = ''
  arr1.value = []
  getModuleData(e, index)
}

const getModuleData = (e, index) => {
  if (e) {
    apiGetModule1({ projectEname: e }).then((res) => {
      if (res.data.success) {
        Array.isArray(res.data.data) &&
          res.data.data.forEach((item) => {
            // state.dataList.forEach((item1,index)=>{

            // })
            // item.label = item.moduleCname2
            item.label = `${item.moduleEname1}`
            item.value = item.moduleEname1
          })

        if (Array.isArray(res.data.data)) {
          const newArray = res.data.data.map((item) => ({
            label: `${item.moduleEname1}`,
            value: item.moduleEname1,
          }))
          // 找到选定的行并更新其 moduleEname1 选项
          // const selectedRow = tableRef.value.cloneTableData.find((row) => row.projectEname === e)
          const selectedRow = tableRef.value.cloneTableData[index]
          console.log('-----------00006', tableRef.value.cloneTableData)
          if (selectedRow) {
            selectedRow.moduleEname1Options = newArray
          }
          arr1.value = newArray
          //  arr1.value=newArray
          // state.dataList = state.dataList.map((item) => ({
          //   ...item,
          //   moduleEname1Options:newArray , // 添加新属性
          // }));
          // const selectedRowIndex = state.dataList.findIndex((row) => row.project === e);
          //   if (selectedRowIndex !== -1) {
          //     arr1.value[selectedRowIndex] = newArray;
          //   }

          // arr1.value=newArray
          // state.dataList
          console.log(arr1, '查看arr1')
        }
      }
    })
  }
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
// 隐藏搜索项有值的个数
const searchItemCount = computed(() => {
  let filledCount = 0
  const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
  // 下面是从第三项起计算常规搜索条件有值个树
  // 获取state.query的所有keys
  const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
  if (queryKeys.length < 3) return 0
  // 从第三项开始计算
  queryKeys.slice(2).forEach((key) => {
    if (state.query[key] !== '' && state.query[key] !== null) {
      filledCount++
    }
  })
  return filledCount
})
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if(type == 'page'){
    state.query.current = pageConfig.currentPage
  }else{
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  apiGettipcodeMaintQuery(state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiGettipcodeMaintSave(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  console.log(checkedRows.value, '0000')
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.id) ids.push(item?.id)
    })
  isTableLoading.value = true
  apiGettipcodeMaintDel(ids)
    .then((res) => {
      isTableLoading.value = false
      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave(data, 'add')
}
watch(
  () => columns,
  (newValue) => {},
  { deep: true, immediate: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
const arr2 = ref([])
const getProjectname = () => {
  apiGetbackproject().then((res) => {
    // console.log(res.data.data,99999999999999999999)
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `[${item.projectEname}] ${item.projectCname}`
          item.value = item.projectEname
        })

      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `${item.projectEname}`,
          value: item.projectEname,
        }))

        // columns[3].editConfig.options = newArray
        // columns.editConfig.options = newArray
        // 在 DOM 更新后执行的操作
        arr2.value = newArray
        console.log(arr2.value)
      }
    }
  })
  // 如果是下拉框字段，触发接口获取选项
  //  this.fetchOptions(row旧值); // 根据旧值或上下文决定如何查询
}
const arr3 = ref([])
const getProjectlang = () => {
  apiQueryCodeitem({ codesetCode: 'iplat.lang' }).then((res) => {
    if (res.data.success) {
      Array.isArray(res.data.data) &&
        res.data.data.forEach((item) => {
          // item.label = item.moduleCname2
          item.label = `${item.itemCode}  ${item.itemCname}`
          item.value = item.itemCode
        })
      if (Array.isArray(res.data.data)) {
        const newArray = res.data.data.map((item) => ({
          label: `${item.itemCode}  ${item.itemCname}`,
          value: item.itemCode,
        }))
        arr3.value = newArray
      }
    }
  })
}
onMounted(() => {
  // 获取查询条件缓存
  getProjectlang()
  getProjectname()
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn()
})
</script>
<style lang="less" scoped></style>
